/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-02-27 16:08:44
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-02-28 11:08:19
 */
const crypto = require('crypto')

// 延时函数
const sleep = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(true) }, time)
  })
}

// js对象转url
const obj2url = (obj) => {
  if (!obj) return ''
  let params = [];
  Object.entries(obj).forEach(([key, val]) => {
    if (val === 0 || val) params.push(encodeURIComponent(key) + "=" + encodeURIComponent(val))
  })
  return params.join("&")
}

// AES CBC加密
const aesEncrypt = (data, key, iv) => {
  var cipherChunks = []
  var cipher = crypto.createCipheriv('aes-128-cbc', key, iv)
  cipher.setAutoPadding(true)
  cipherChunks.push(cipher.update(data, 'utf8', 'base64'))
  cipherChunks.push(cipher.final('base64'))
  return cipherChunks.join('')
}

// AES CBC解密
const aesDecrypt = (data, key, iv) => {
  var cipherChunks = []
  var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv)
  decipher.setAutoPadding(true)
  cipherChunks.push(decipher.update(data, 'base64', 'utf8'))
  cipherChunks.push(decipher.final('utf8'));
  return cipherChunks.join('')
}

// md5
const md5 = (str) => {
  const hash = crypto.createHash('md5')
  hash.update(str)
  return hash.digest('hex')
}

// 生成指定长度的随机字符串
function randomStr(range) {
  let baseStr = 'AaBbCcDdEeFfGgHhiJjKkLlMmNnPpQqRrSsTtUuVvWwXxYyZz9876543210'
  let str = '', num = 0, len = baseStr.length
  for (num = 0; num < range; num++) {
    str += baseStr.charAt(Math.floor(Math.random() * len))
  }
  return str
}

// 环境判断
const isDev = () => {
  let env = process.env.NODE_ENV
  return env ? env.trim() === 'development' : false
}

module.exports = { sleep, obj2url, aesEncrypt, aesDecrypt, md5, randomStr, isDev }